package com.ztn.iot.zhonghaichi.push;

import com.ztn.base.util.common.HttpClientTool;
import com.ztn.base.util.common.JsonTool;
import com.ztn.base.util.common.TimeTool;
import com.ztn.iot.zhonghaichi.fun.SensorFun;
import com.ztn.iot.zhonghaichi.properties.ZhcProperties;
import com.ztn.iot.zhonghaichi.push.req.PushCameraPictureReq;
import com.ztn.iot.zhonghaichi.push.res.PushRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
@Component
public class CameraPushApi {

    @Autowired
    private ZhcProperties zhcProperties;

    @Autowired
    private SensorFun sensorFun;

    public void pushPicture(String siteCode, String base64Str) {
        if (!StringUtils.hasText(siteCode)) {
            log.error("!StringUtils.hasText(siteCode)");
            return;
        }
        final String date = TimeTool.timeStamp2Date(TimeTool.time());
        PushCameraPictureReq req = new PushCameraPictureReq();
        req.setBase64Content(base64Str);
        req.setSTCD(siteCode);
        req.setTM(date);
        zhcProperties.getZhcAuths().forEach(zhmAuth -> {
            Map<String, Object> headers = TokenGetApi.getHeaders(zhmAuth.getBaseUrl());
            if (null == headers) {
                return;
            }
            final PushRes pushRes = HttpClientTool.postJsonStrWithHeaderForObject(zhmAuth.getBaseUrl() + PushCameraPictureReq.URL, JsonTool.toJson(req), headers, PushRes.class,null);
            if (null == pushRes) {
                log.error("{} null==pushRes", zhmAuth.getBaseUrl());
                log.error("{} {}", req.getSTCD(), req.getTM());
            } else if (pushRes.getCode() != 200) {
                log.error("{} pushRes.getCode() != 200", zhmAuth.getBaseUrl());
                log.error("{} {}", req.getSTCD(), req.getTM());
                System.out.println(pushRes);
            } else if(pushRes.getCode() == 401){
                sensorFun.updateToken();
            }
        });

    }

}
